package com.hz.ruoyilgorder.canal;

import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.client.CanalConnectors;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.alibaba.otter.canal.protocol.CanalEntry.*;
import com.alibaba.otter.canal.protocol.Message;
import com.hz.ruoyilgorder.rabbitmq.MessageProducer;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.concurrent.Executor;

/**
 * @description: TODO
     * @param
     * @return  springboot启动
     * @author: yzw
     * @date: 2025/3/16 11:14
 */

@Component
@EnableAsync
public class CannalClient implements InitializingBean {
    @Autowired
    private MessageProducer messageProducer;  // 注入 RabbitMQ 生产者
    private final static int BATCH_SIZE = 1000;

    @PostConstruct
    public void init() {
        Executor executor = createExecutor();
        executor.execute(this::startCanalClient);
    }

    private Executor createExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(4);  // 线程数
        executor.setMaxPoolSize(6);
        executor.setQueueCapacity(10);
        executor.initialize();
        return executor;
    }

    public void startCanalClient() {
        CanalConnector connector = CanalConnectors.newSingleConnector(new InetSocketAddress("192.168.149.73", 11111), "example", "", "");
        try {
            connector.connect();
            // 订阅数据库表，全部表
            connector.subscribe("ry-cloud.lg_cold_storage");
            connector.rollback();
            while (true) {
                Message message = connector.getWithoutAck(BATCH_SIZE);
                long batchId = message.getId();
                int size = message.getEntries().size();
                if (batchId == -1 || size == 0) {
                    Thread.sleep(2000);
                } else {
                    this.printEntry(message.getEntries());  // 'this' 是当前实例
                }
                connector.ack(batchId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            connector.disconnect();
        }
    }

    private  void printEntry(List<CanalEntry.Entry> entrys) {
        for (Entry entry : entrys) {
            if (entry.getEntryType() == EntryType.TRANSACTIONBEGIN || entry.getEntryType() == EntryType.TRANSACTIONEND) {
                //开启/关闭事务的实体类型，跳过
                continue;
            }
            //RowChange对象，包含了一行数据变化的所有特征
            //比如isDdl 是否是ddl变更操作 sql 具体的ddl sql beforeColumns afterColumns 变更前后的数据字段等等
            RowChange rowChage;
            try {
                rowChage = RowChange.parseFrom(entry.getStoreValue());
            } catch (Exception e) {
                throw new RuntimeException("ERROR ## parser of eromanga-event has an error , data:" + entry.toString(), e);
            }
            //获取操作类型：insert/update/delete类型
            EventType eventType = rowChage.getEventType();

            //判断是否是DDL语句
            if (rowChage.getIsDdl()) {
                System.out.println("================》;isDdl: true,sql:" + rowChage.getSql());
            }

            // 组装变更信息 发送到队列
            StringBuilder message = new StringBuilder();

            for (RowData rowData : rowChage.getRowDatasList()) {
                //如果是删除语句
                if (eventType == EventType.DELETE) {
                    message.append("0");

                } else if (eventType == EventType.INSERT) {
                    message.append("1");

                } else {
                    message.append("2");

                }
                // 发送变更消息到 RabbitMQ
                messageProducer.sendToQueue(message.toString());
            }
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }



    private static String getChangedColumns(List<Column> beforeColumns, List<Column> afterColumns) {
        StringBuilder changedColumns = new StringBuilder();

        for (int i = 0; i < beforeColumns.size(); i++) {
            Column before = beforeColumns.get(i);
            Column after = afterColumns.get(i);
            // 判断该列是否更新
            if (after.getUpdated()) {
                // 如果列发生变化，可以输出列的相关信息
                if (before.getName().equals("id")) {
                    // 如果列发生变化，获取列的相关信息
                    changedColumns.append("Column: ").append(", Before: ").append(before.getValue())
                            .append(", After: ").append(after.getValue()).append("; ");
                }
            }
        }

        return changedColumns.toString();  // 返回发生变化的列的信息
    }

}
